package user

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/user"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"strings"
	"time"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserSurveyEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUserSurveyEditLogic - 新增/修改用户问卷
func NewUserSurveyEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserSurveyEditLogic {
	return &UserSurveyEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserSurveyEditLogic) UserSurveyEdit(req *types.UserSurveyEditRequest) error {
	// 创建实例
	userSurveyInfoDao := user.NewUserSurveyDao(l.ctx, l.svcCtx)

	// 组装参数
	userSurveyInfo := &ent.HzUserSurvey{
		UserSurveyPhone: req.UserSurveyPhone,
		UserSurveyName:  req.UserSurveyName,
		UserSurveySex:   req.UserSurveySex,
		UserSurveyType:  req.UserSurveyType,
		UpdateAt:        time.Now().Unix(),
	}

	// 新增问卷邀请信息
	if req.Type == constant.Add {
		userSurveyInfo.CreatedAt = time.Now().Unix()
		err := userSurveyInfoDao.UserSurveyCreate(userSurveyInfo, nil)
		if err != nil {
			if strings.Contains(err.Error(), "Error 1062 (23000)") && strings.Contains(err.Error(), "Duplicate entry") {
				return xerr.ErrCodeMsg(xerr.ServerDataRepeatError, fmt.Sprintf("违反实体唯一约束: %v", err))
			}
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("添加用户问卷失败: %v", err))
		}

	}

	// 编辑问卷邀请信息
	if req.Type == constant.Edit && req.Id != 0 {
		userSurveyInfo.ID = int(req.Id)
		if err := userSurveyInfoDao.UserSurveyUpdate(userSurveyInfo, nil); err != nil {
			return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("修改用户问卷失败: %v", err))
		}
	}

	return nil
}
